package com.jcxh.sg_exam.controller;

import com.alibaba.excel.EasyExcel;
import com.jcxh.sg_exam.pojo.*;
import com.jcxh.sg_exam.pojo.download.DownLoadDanxuan;
import com.jcxh.sg_exam.pojo.download.DownLoadDuoxuan;
import com.jcxh.sg_exam.pojo.download.DownLoadKaochangUser;
import com.jcxh.sg_exam.pojo.download.DownLoadPanduan;
import com.jcxh.sg_exam.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author 鹏少
 * @Date 2024/8/8
 * @Date 10:59
 */
@RestController
@RequestMapping("admin/export")
@Api(tags = "导出接口")
@Slf4j
public class ExportController {

    @Autowired
    private UserService userService;

    @Autowired
    private DanxuanService danxuanService;

    @Autowired
    private DuoxuanService duoxuanService;

    @Autowired
    private PanduanService panduanService;

    @Autowired
    private ShicaoService shicaoService;

    @Autowired
    private KaochangUserService kaochangUserService;

    @Autowired
    private GradeService gradeService;

    @Autowired
    private KaochangService kaochangService;

    @Autowired
    private NewShicaoService newShicaoService;


    /**
     * 人员导出
     *
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "人员导出", produces = "application/octet-stream")
    @GetMapping("/users")
    public void export(HttpServletResponse response) {
        try {

            List<User> userList = userService.lambdaQuery().getBaseMapper().selectList(null);

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("人员信息导出", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), User.class).sheet("人员信息导出").doWrite(userList);
        } catch (Exception e) {
            log.error("导出失败: {}", e.getMessage());
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出失败");
            } catch (IOException ioException) {
                log.error("Error sending error response: {}", ioException.getMessage());
            }
        }
    }

    /**
     * 单选题导出
     *
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "单选题导出", produces = "application/octet-stream")
    @GetMapping("/danxuan")
    public void exportDanxuan(HttpServletResponse response) {
        try {
            List<DownLoadDanxuan> list = new ArrayList<>();
            List<Danxuan> danxuanList = danxuanService.lambdaQuery().getBaseMapper().selectList(null);
            // 遍历 danxuanList，将 Danxuan 对象转换为 DownLoadDanxuan 对象
            for (Danxuan danxuan : danxuanList) {
                DownLoadDanxuan downDanxuan = new DownLoadDanxuan();
                BeanUtils.copyProperties(danxuan, downDanxuan);
                list.add(downDanxuan);
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("单选题导出", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), DownLoadDanxuan.class).sheet("单选题导出").doWrite(list);
        } catch (Exception e) {
            log.error("导出失败: {}", e.getMessage());
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出失败");
            } catch (IOException ioException) {
                log.error("Error sending error response: {}", ioException.getMessage());
            }
        }
    }


    /**
     * 多选题导出
     *
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "多选题导出", produces = "application/octet-stream")
    @GetMapping("/duoxuan")
    public void exportDuoxuan(HttpServletResponse response) {
        try {
            List<DownLoadDuoxuan> list = new ArrayList<>();
            List<Duoxuan> duoxuanList = duoxuanService.lambdaQuery().getBaseMapper().selectList(null);
            // 遍历 duoxuanList，将 Duoxuan 对象转换为 DownLoadDuoxuan 对象
            for (Duoxuan duoxuan : duoxuanList) {
                DownLoadDuoxuan downDuoxuan = new DownLoadDuoxuan();
                BeanUtils.copyProperties(duoxuan, downDuoxuan);
                list.add(downDuoxuan);
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("多选题导出", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), DownLoadDuoxuan.class).sheet("多选题导出").doWrite(list);
        } catch (Exception e) {
            log.error("导出失败: {}", e.getMessage());
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出失败");
            } catch (IOException ioException) {
                log.error("Error sending error response: {}", ioException.getMessage());
            }
        }
    }

    /**
     * 判断题导出
     *
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "判断题导出", produces = "application/octet-stream")
    @GetMapping("/panduan")
    public void exportPanduan(HttpServletResponse response) {
        try {
            List<DownLoadPanduan> list = new ArrayList<>();
            List<Panduan> panduanList = panduanService.lambdaQuery().getBaseMapper().selectList(null);
            // 遍历 panduanList，将 Panduan 对象转换为 DownLoadPanduan 对象
            for (Panduan panduan : panduanList) {
                DownLoadPanduan downPanduan = new DownLoadPanduan();
                BeanUtils.copyProperties(panduan, downPanduan);
                list.add(downPanduan);
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("判断题导出", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), DownLoadPanduan.class).sheet("判断题导出").doWrite(list);
        } catch (Exception e) {
            log.error("导出失败: {}", e.getMessage());
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出失败");
            } catch (IOException ioException) {
                log.error("Error sending error response: {}", ioException.getMessage());
            }
        }


    }

    /**
     * 判断题导出
     *
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "考试成绩导出", produces = "application/octet-stream")
    @GetMapping("/score")
    public void exportScore(HttpServletResponse response) {
        try {
            List<DownLoadKaochangUser> list = new ArrayList<>();
            List<KaochangUser> kaochangUserList = kaochangUserService.lambdaQuery().getBaseMapper().selectList(null);
            kaochangUserList.forEach(s -> {
                Kaochang kaochang = kaochangService.lambdaQuery().eq(Kaochang::getId, s.getKaochangId()).one();
                s.setKaochangName(kaochang.getType());
            });
            // 遍历 panduanList，将 Panduan 对象转换为 DownLoadPanduan 对象
            for (KaochangUser kaochangUser : kaochangUserList) {
                DownLoadKaochangUser downLoadKaochangUser = new DownLoadKaochangUser();
                BeanUtils.copyProperties(kaochangUser, downLoadKaochangUser);
                list.add(downLoadKaochangUser);
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("考试成绩导出", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), DownLoadKaochangUser.class).sheet("考试成绩导出").doWrite(list);
        } catch (Exception e) {
            log.error("导出失败: {}", e.getMessage());
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出失败");
            } catch (IOException ioException) {
                log.error("Error sending error response: {}", ioException.getMessage());
            }
        }


    }


    /**
     * 实操题导出
     *
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "实操题导出", produces = "application/octet-stream")
    @GetMapping("/shicao")
    public void exportShicao(HttpServletResponse response) {
        try {

            List<Shicao> shicaoList = shicaoService.lambdaQuery().getBaseMapper().selectList(null);

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("实操题导出", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), Shicao.class).sheet("实操题导出").doWrite(shicaoList);
        } catch (Exception e) {
            log.error("导出失败: {}", e.getMessage());
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出失败");
            } catch (IOException ioException) {
                log.error("Error sending error response: {}", ioException.getMessage());
            }
        }


    }


    /**
     * 理论成绩+实操成绩导出
     *
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "理论成绩+实操成绩导出", produces = "application/octet-stream")
    @GetMapping("/exportAll")
    public void exportAll(HttpServletResponse response) {

        try {

            List<Grade> gradeList = gradeService.exportAll();

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("理论成绩+实操成绩导出", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), Grade.class).sheet("理论成绩+实操成绩导出").doWrite(gradeList);
        } catch (Exception e) {
            log.error("导出失败: {}", e.getMessage());
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出失败");
            } catch (IOException ioException) {
                log.error("Error sending error response: {}", ioException.getMessage());
            }
        }
    }


        /**
         * 实操成绩导出
         *
         * @param response
         * @throws IOException
         */
        @ApiOperation(value = "实操成绩导出", produces = "application/octet-stream")
        @GetMapping("/exportShicaoScore")
        public void exportShicaoScore (HttpServletResponse response){

            try {

                List<NewShicao> newShicaoList = newShicaoService.lambdaQuery().list();

                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("utf-8");
                // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
                String fileName = URLEncoder.encode("实操成绩导出", "UTF-8").replaceAll("\\+", "%20");
                response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
                EasyExcel.write(response.getOutputStream(), NewShicao.class).sheet("实操成绩导出").doWrite(newShicaoList);
            } catch (Exception e) {
                log.error("导出失败: {}", e.getMessage());
                try {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出失败");
                } catch (IOException ioException) {
                    log.error("Error sending error response: {}", ioException.getMessage());
                }
            }


        }


    }
